﻿using System.Web.Mvc;
using System.Linq;
using QSASPMVCApplicationCSharp.Models;
using System;
using QSASPMVCApplicationCSharp.Data.Interfaces;
using QSASPMVCApplicationCSharp.Data;

namespace QSASPMVCApplicationCSharp.Controllers
{
   public class ProductsController : Controller
   {
	  private readonly IProductRepository productRepository;
      public ProductsController()
      {
		  productRepository = new SessionProductRepository();
	  }

	  //
	  // Browse Action
	  // 
	  // URL:  /Products/Browse
	  //
	  public object Browse()
	  {
		  var products = productRepository.GetProducts().ToList();

		  return View(products);
	  }


	  //
	  // Create Action
	  // 
	  // URL:  /Products/Create
	  //

	  [AcceptVerbs("GET")]
	  public object Create()
	  {
		  return View(new Product());
	  }

	  [AcceptVerbs("POST")]
	  public object Create(Product product)
	  {
		  // redisplay form immediately if there are input format errors
		  if (!ViewData.ModelState.IsValid)
		  {
		      return View(product);
		  }

		  // redisplay if there are validation errors
		  if (!product.IsValid)
		  {
			  ViewData["Message"] = "Oops: Error";
			  // UpdateModelStateWithViolations(product, ViewData.ModelState);
			  return View(product);
		  }

		  productRepository.SaveProduct(product);
		  return RedirectToAction("Browse");
	  }


	  //
	  // Edit Action
	  // 
	  // URL:  /Products/Edit/5
	  //       /Products/Edit/3
	  //

	  [AcceptVerbs("GET")]
	  public object Edit(int id)
	  {

		  var product = productRepository.GetProduct(id);

		  return View(product);
	  }

	  [AcceptVerbs("POST")]
	  public object Edit()
	  {
		  var id = int.Parse(Request.Form["Id"]);
		  var product = productRepository.GetProduct(id);

		  try
		  {
			  UpdateModel(product, new[] { "ProductName", "UnitPrice", "Discontinued", "ReorderLevel" });
			  TempData["Message"] = "Product Updated!";
			  return RedirectToAction("Edit", new { id = product.ProductId });
		  }
		  catch (Exception error)
		  {
			  TempData["Message"] = "Oops - problems";

			 // UpdateModelStateWithViolations(product, ViewData.ModelState);

			  return View(product);
		  }
	  }

   }
}